package com.ezops.gateway;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

import com.ezops.util.LoggerUtil;

public class MqListener implements MessageListener {

	private static final Logger logger = LoggerFactory
			.getLogger(MqListener.class);
	private Map<String, ResponseHandler> registeredHandler;

	/**
	 * This class implements org.springframework.amqp.core.MessageListener. It
	 * is tied to TUTORIAL_EXCHANGE and listing to an anonomous queue which
	 * picks up message in the TUTORIAL_EXCHANGE with a routing pattern of
	 * my.routingkey.1 specified in rabbt-listener-contet.xml file.
	 */
	public void onMessage(Message message) {
		String messageBody = new String(message.getBody());
		try {
			logger.info(
					"Message received for report request with header [{}] ",
					LoggerUtil.getLoggableFormat(message.getMessageProperties()
							.getHeaders()));

			ResponseHandler handler = registeredHandler.get(message
					.getMessageProperties().getMessageId());
			if (handler != null) {
				// TODO - This can be done in background thread.
				handler.handle(messageBody);
				registeredHandler.remove(handler.getMessageIdentifierKey());
			}
		} catch (Exception e) {
			// Till the time dead letter queue or limit been put on redelivery
			logger.error(
					"Error while processing the report response from MQ. Reason - {}",
					e.getMessage());
		}
	}

	/**
	 * Register the call back handler to receive the response back.
	 * 
	 * @param handler
	 */
	public void register(ResponseHandler handler) {

		if (registeredHandler == null) {
			registeredHandler = new ConcurrentHashMap<>();
		}
		registeredHandler.put(handler.getMessageIdentifierKey(), handler);
	}

}
